import pymysql
from django.shortcuts import HttpResponse, render, redirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
import json
from django.http import JsonResponse
from qiniu import Auth, put_file, etag

conn = pymysql.connect("139.196.136.63", "user1", "123456", "kuyue", charset='utf8')
cursor = conn.cursor(pymysql.cursors.DictCursor)


def Header(request):
    return render(request, 'Header.html')


def Details(request):
    return render(request, 'Details.html')


def Talk(request):
    return render(request, 'Talk.html')


def TalkDetails(request):
    return render(request, 'TalkDetails.html')


def MyTalk(request):
    return render(request, 'MyTalk.html')


def Read(request):
    cursor.execute("select chapter_name,chapter_content from n_chapter")
    lst = cursor.fetchall()
    print(lst[0]['chapter_name'])
    print(lst[0]['chapter_content'])
    # conn.close()
    return render(request, 'Read.html', {'lst': lst[0]})


# 马荣
def main(request):
    sql='select * from n_bookinfo,n_kind,n_user where n_bookinfo.kind_id=n_kind.kind_id and n_bookinfo.user_id = n_user.user_id   order by book_ticketcount desc'
    cursor.execute(sql)
    tc=cursor.fetchall()
    tc_1=tc[0]
    tc=tc[1:10]
    # print(tc)
    sql = 'select * from n_bookinfo,n_kind,n_user where n_bookinfo.kind_id=n_kind.kind_id and n_bookinfo.user_id = n_user.user_id order by book_sellcount desc'
    cursor.execute(sql)
    sc = cursor.fetchall()
    sc_1 = sc[0]
    sc = sc[1:10]
    sql = 'select * from n_bookinfo,n_kind,n_user where n_bookinfo.kind_id=n_kind.kind_id and n_bookinfo.user_id = n_user.user_id order by book_words desc'
    cursor.execute(sql)
    bw = cursor.fetchall()
    bw_1 = bw[0]
    bw = bw[1:10]
    sql = 'select * from n_bookinfo,n_kind,n_user where n_bookinfo.kind_id=n_kind.kind_id and n_bookinfo.user_id = n_user.user_id order by book_clickcount desc'
    cursor.execute(sql)
    cc = cursor.fetchall()
    cc_1 = cc[0]
    cc = cc[1:10]
    sql = 'select * from n_bookinfo,n_kind,n_user where n_bookinfo.kind_id=n_kind.kind_id and n_bookinfo.user_id = n_user.user_id order by book_estimate desc'
    cursor.execute(sql)
    be = cursor.fetchall()
    be = be[0:10]
    sql = 'select * from n_bookinfo,n_kind,n_user where n_bookinfo.kind_id=n_kind.kind_id and n_bookinfo.user_id = n_user.user_id order by book_estimatecount desc'
    cursor.execute(sql)
    ec = cursor.fetchall()
    ec1 = ec[0:3]
    ec2 = ec[3:6]
    ec3 = ec[6:9]
    i=['01','02','03','04','05','06','07','08','09','10']
    for i in ec:
        # i['book_introduction']=i['book_introduction'][0:30]

        i['book_introduction']=i['book_introduction'].strip()[0:30].replace(' ', '').replace('\n', '').replace('\t', '').replace('\r', '')
    return render(request, 'main.html', {'tc_1':tc_1,'tc':tc,'sc_1':sc_1,'sc':sc,'bw_1':bw_1,'bw':bw,'cc_1':cc_1,'cc':cc,'be':be,'ec1':ec1,'i':i,'ec2':ec2,'ec3':ec3})


def main2(request):
    i = 1
    return render(request, 'main2.html', {'i': 1})


def ranking(request):
    i = 1
    return render(request, 'ranking list.html', {'i': 1})


def ranking2(request):
    try:
        if request.method == 'POST':
            sid = request.POST.get('sid')
            sid = int(sid)
            print(sid)
            list1 = []
            db = pymysql.connect("localhost", "root", "root", "test", charset='utf8')
            cursor = db.cursor()
            sql = 'select name from cat'
            cursor.execute(sql)
            result = cursor.fetchall()
            print(len(result))
            if len(result) % 5 == 0:
                length = len(result) // 5
            else:
                length = len(result) // 5 + 1
            print(length)
            for x in range(1, length + 1):
                {
                    list1.append(x)
                }
            z = 1
            m = 1
            n = len(list1)
            if sid < 1:
                sid = 1
            elif sid > len(list1):
                sid = len(list1)
            if sid - 2 > 1 and sid + 2 < len(list1):
                z = 3
                m = 1
                n = len(list1)
                list1 = list1[sid - 3:sid + 2]
            elif sid - 2 == 1 and sid + 2 < len(list1):
                z = 1
                m = 1
                n = len(list1)
                list1 = list1[sid - 3:sid + 2]
            elif sid - 2 > 1 and sid + 2 == len(list1):
                z = 2
                m = 1
                n = len(list1)
                list1 = list1[sid - 3:sid + 2]
            elif sid - 2 <= 0 and sid + 2 < len(list1):
                z = 1
                m = 1
                n = len(list1)
                list1 = list1[0:sid + 2]
            elif sid - 2 > 1 and sid + 2 > len(list1):
                z = 2
                m = 1
                n = len(list1)
                list1 = list1[sid - 3:sid + 2]
            print(list1)
            a = 5 * (sid - 1)
            b = 5 * sid
            print(a, b)
            result = result[a:b]
            print(result)
            return render(request, 'ranking list2.html',
                          {'result': result, 'list1': list1, 'sid': sid, 'length': length, 'z': z, 'm': m, 'n': n})
        elif request.method == 'GET':
            sid = request.GET.get('sid')
            a = sid.split(',')
            sid = int(a[0])
            b = a[1].split('=')
            snum = int(b[1])
            print(sid, snum)
            sid = sid + snum
            sid = int(sid)
            list1 = []
            db = pymysql.connect("localhost", "root", "root", "test", charset='utf8')
            cursor = db.cursor()
            sql = 'select name from cat'
            cursor.execute(sql)
            result = cursor.fetchall()
            print(len(result))
            if len(result) % 5 == 0:
                length = len(result) // 5
            else:
                length = len(result) // 5 + 1
            print(length)
            for x in range(1, length + 1):
                {
                    list1.append(x)
                }
            z = 1
            m = 1
            n = len(list1)
            if sid - 2 > 1 and sid + 2 < len(list1):
                z = 3
                m = 1
                n = len(list1)
                list1 = list1[sid - 3:sid + 2]
            elif sid - 2 == 1 and sid + 2 < len(list1):
                z = 1
                m = 1
                n = len(list1)
                list1 = list1[sid - 3:sid + 2]
            elif sid - 2 > 1 and sid + 2 == len(list1):
                z = 2
                m = 1
                n = len(list1)
                list1 = list1[sid - 3:sid + 2]
            elif sid - 2 <= 0 and sid + 2 < len(list1):
                z = 1
                m = 1
                n = len(list1)
                list1 = list1[0:sid + 2]
            elif sid - 2 > 1 and sid + 2 > len(list1):
                z = 2
                m = 1
                n = len(list1)
                list1 = list1[sid - 3:sid + 2]
            print(list1)
            a = 5 * (sid - 1)
            b = 5 * sid
            print(a, b)
            result = result[a:b]
            print(result)
            return render(request, 'ranking list2.html',
                          {'result': result, 'list1': list1, 'sid': sid, 'length': length, 'z': z, 'm': m, 'n': n})
    except:
        sid = 1
        list1 = []
        db = pymysql.connect(host="localhost", port=3306, user="root", password="root", db="test",
                             charset='utf8')
        cursor = db.cursor()
        sql = 'select name from cat'
        cursor.execute(sql)
        result = cursor.fetchall()
        if len(result) % 5 == 0:
            length = len(result) // 5
        else:
            length = len(result) // 5 + 1
        for x in range(1, length + 1):
            {
                list1.append(x)
            }
        print(list1)
        a = 5 * (sid - 1)
        b = 5 * sid
        print(a, b)
        result = result[a:b]
        print(result)
        z = 1
        m = 1
        n = len(list1)
        list1 = list1[0:3]
        return render(request, 'ranking list2.html',
                      {'result': result, 'list1': list1, 'sid': sid, 'z': z, 'm': m, 'n': n})


def search(request):
    i = 1
    return render(request, 'search.html', {'i': 1})


def timefree(request):
    i = 1
    return render(request, 'timefree.html', {'i': 1})


def index(request):
    # 获取Book数据表中的所有记录
    book_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

    # 生成paginator对象,定义每页显示10条记录
    paginator = Paginator(book_list, 10)

    # 从前端获取当前的页码数,默认为1
    page = request.GET.get('page', 1)

    # 把当前的页码数转换成整数类型
    currentPage = int(page)

    try:
        print(page)
        book_list = paginator.page(page)  # 获取当前页码的记录
    except PageNotAnInteger:
        book_list = paginator.page(1)  # 如果用户输入的页码不是整数时,显示第1页的内容
    except EmptyPage:
        book_list = paginator.page(paginator.num_pages)  # 如果用户输入的页数不在系统的页码列表中时,显示最后一页的内容

    return render(request, "index.html", locals())


def self(request):
    i = 1
    v = request.POST.get('i')
    return render(request, 'self.html', {'i': v})


def selfset(request):
    if request.method == "GET":
        return render(request, 'selfset.html')
    else:
        File = request.FILES.get("img")
        with open('media/upload/img/' + File.name, 'wb')as f:  # with open 无法创建文件夹，需要自己创建
            for chunk in File.chunks():
                f.write(chunk)
        access_key = 'O4uhB24lIhk5B_VR1Tj6IQ1pF0kKA18aIpEzs3Kv'
        secret_key = 'aEEnRGPsAGIRZCobHxBuRmao0Z3wQfi7NyQxzZJV'
        q = Auth(access_key, secret_key)
        bucket_name = 'tupian'
        key = File.name
        localfile = r"media/upload/img/" + File.name
        token = q.upload_token(bucket_name, key)
        ret, info = put_file(token, key, localfile)
        src = 'http://files.g4.xmgc360.com/' + File.name
        cursor.execute("update n_user set user_image=%s where user_id=%s", [src, 1])
        conn.commit()
    return render(request, 'self.html', {'src': src})


# 周磊
def register(request):
    return render(request, 'classify-row.html')


def classify(request):
    return render(request, 'classify.html')




def row(request):
    return render(request, 'classify-row.html')


def wanben(request):
    return render(request, 'wanben.html')


def free(request):
    return render(request, 'time-free.html')


def freeAll(request):
    return render(request, 'freeAll.html')


def shoplog(request):
    return render(request, 'shoplog.html')


def shop(request):
    return render(request, 'shopping.html')


def dashang(request):
    return render(request, 'dashang.html')


def pay(request):
    return render(request, 'pay.html')


# 周永辉
def author(request):
    return render(request, 'author.html')


def author_look(request):
    return render(request, 'author_look.html')


def login(request):
    return render(request, 'login.html')


def register(request):
    return render(request, 'register.html')


# 测试
def test1(request):
    if request.method == "GET":
        return render(request, 'test1.html')
    # # else:
    # # content = request.POST('content')
    # # print(content)
    # # print(type(content))
    # # return render(request, 'main.html')
    # else:
    #     print(123123213)
    # else:
    #     #         print(4511231)
    #     html = request.POST.get("html")
    #     print(html)
    #     ret = 1234
    #     return HttpResponse(json.dumps(ret))
    #         print(data)
    #         print(host)
    #         return HttpResponse(json.dumps(host))
    #         # return render(request, 'main.html')
    if request.is_ajax():
        print(213123123)
        data = request.POST
        host = request.POST.get("host")
        print(data['html'])
        print(host)
        response = JsonResponse({"host": data['html']})
        return response
